package com.wzy.vx.service.impl;

import com.wzy.vx.DTO.CateDTO;
import com.wzy.vx.DTO.OrderDTO;
import com.wzy.vx.WebSocket.WebSocket;
import com.wzy.vx.converter.OrderMasterConOrderDTO;
import com.wzy.vx.dataobject.OrderDetail;
import com.wzy.vx.dataobject.OrderMaster;
import com.wzy.vx.dataobject.ProductInfo;
import com.wzy.vx.enums.OrderStatusEnum;
import com.wzy.vx.enums.PayStatusEnum;
import com.wzy.vx.enums.ResuletEnum;
import com.wzy.vx.Utils.*;
import com.wzy.vx.exception.SellException;
import com.wzy.vx.repository.OrderDetailRepository;
import com.wzy.vx.repository.OrderMasterRepository;
import com.wzy.vx.service.OrderService;
import com.wzy.vx.service.PayService;
import com.wzy.vx.service.ProductService;
import com.wzy.vx.service.PushMsg;
import org.hibernate.criterion.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: vx
 * @Package: com.wzy.vx.service.impl
 * @ClassName: OrderServiceImpl
 * @Author: Administrator
 * @Description: 其实
 * @Date: 2019/3/12 18:35
 * @Version: 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService  productService;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private PayService payService;

    private static Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private PushMsg pushMsg;//推送消息

    @Autowired
    private WebSocket webSocket;


    @Override
    @Transactional//事务 异常回滚
    public OrderDTO create(OrderDTO orderDTO) {
        //1.查询商品 数量 价格
        String orderId = KeyUtil.unKey();
        BigDecimal totalPrice = new BigDecimal(BigInteger.ZERO);
        List<CateDTO> cateDTOList = new ArrayList<>();
        for (OrderDetail orderDetail:orderDTO.getOrderMasterList()) {
            ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
            if (productInfo == null) {
             throw new SellException(ResuletEnum.PRODUCT_NOT_EXIST);
            }

        //2.计算订单总价
           // totalPrice  = BigDecimalPriceUtil.mul(productInfo.getProductPrice().doubleValue(),orderDetail.getProductQuantity().doubleValue());
            totalPrice = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(totalPrice);
            orderDetail.setDetailId(KeyUtil.unKey());
            orderDetail.setOrderId(orderId);
            //// 拷贝 将pro->order中去 订单详情入库
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetailRepository.save(orderDetail);

            CateDTO cateDTO = new CateDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
            cateDTOList.add(cateDTO);
        }
        //3.写入数据库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(totalPrice);
        orderMaster.setOrderStatus(0);
        orderMaster.setPayStatus(0);
        orderMasterRepository.save(orderMaster);
        //4.如果下单成功减少库存
        productService.descStock(cateDTOList);

        //发送websocket
        webSocket.sendMessage("新订单"+orderDTO.getOrderId());

        return orderDTO;
    }

    @Override
    public OrderDTO findOrder(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findById(orderId).orElse(null);
        if (orderMaster == null) {
            throw new SellException(ResuletEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new SellException(ResuletEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderMasterList(orderDetailList);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> page = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);
        List<OrderDTO> orderDTOList = OrderMasterConOrderDTO.convert(page.getContent());
        return new PageImpl<>(orderDTOList,pageable,page.getTotalElements());
    }

    @Override
    @Transactional
    public OrderDTO cannel(OrderDTO orderDTO) {

        OrderMaster orderMaster = new OrderMaster();
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResuletEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANNEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
            throw new SellException(ResuletEnum.ORDER_UPDATE_FAIL);
        }

        //返回库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderMasterList())) {
            log.error("【取消订单】订单中无商品详情, orderDTO={}", orderDTO);
            throw new SellException(ResuletEnum.ORDER_DETAIL_EMPTY);
        }
        List<CateDTO> cartDTOList = orderDTO.getOrderMasterList().stream()
                .map(e -> new CateDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productService.increaseStock(cartDTOList);

        //如果已支付, 需要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            //to-do 退款
            payService.refund(orderDTO);
        }

        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        //1.判断订单状态
        if (orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW)){
            log.error("[订单状态]不正确{}",orderDTO.getOrderStatus());
            throw  new SellException(ResuletEnum.PRODUCT_STOCK_ERROR);
        }
        //2.修改状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null){
            log.error("[完结订单]更新失败{}",orderMaster);
            throw  new SellException(ResuletEnum.ORDER_UPDATE_FAIL);
        }

        //TO-DO 推送消息
        pushMsg.orderStatus(orderDTO);

        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        //1.判断订单状态
        if (orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("[订单支付完成]订单状态不正确orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw  new SellException(ResuletEnum.PRODUCT_STOCK_ERROR);
        }
        //2.判断 支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
            log.error("[订单支付状态]订单支付状态不正确orderPayStatus={}",orderDTO.getPayStatus());
            throw  new SellException(ResuletEnum.ORDER_PAY_STATUS_ERROR);
        }
        //3.修改订单转态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null){
            log.error("[支付完成订单]但是更新失败{}",orderMaster);
            throw  new SellException(ResuletEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findAllList( Pageable pageable) {
        Page<OrderMaster> page = orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMasterConOrderDTO.convert(page.getContent());
        return new PageImpl<>(orderDTOList,pageable,page.getTotalElements());
    }

}
